package codeTop;

import java.util.List;

public class q445 {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode reverse1 = reverse(l1);
        ListNode reverse2 = reverse(l2);
        int plus = 0;
        ListNode head = new ListNode();
        ListNode p = head;
        while (reverse1 != null && reverse2 != null) {
            p.next = new ListNode((reverse1.val+reverse2.val+plus)%10);
            plus = (reverse1.val+reverse2.val+plus)/10;
            reverse1 = reverse1.next;
            reverse2 = reverse2.next;
            p = p.next;
        }
        while (reverse1 != null) {
            p.next = new ListNode((reverse1.val+plus)%10);
            plus = (reverse1.val+plus)/10;
            reverse1 = reverse1.next;
            p = p.next;
        }
        while (reverse2 != null) {
            p.next = new ListNode((reverse2.val+plus)%10);
            plus = (reverse2.val+plus)/10;
            reverse2 = reverse2.next;
            p = p.next;
        }
        if (plus == 1) {
            p.next = new ListNode(plus);
        }
        return reverse(head.next);
    }
    ListNode reverse(ListNode head){
        ListNode p = null;
        ListNode next = head;
        while (next != null) {
            ListNode temp = next.next;
            next.next = p;
            p = next;
            next = temp;
        }
        return p;
    }
}
